<script setup lang="tsx">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import type { Ref } from 'vue';
import { ref } from 'vue';
import dayjs from 'dayjs';
import type { DataTableRowKey } from 'naive-ui';
import { NButton, NPopconfirm } from 'naive-ui';
import { transDeleteParams } from '@/utils/common';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAuth } from '@/hooks/business/auth';
import { $t } from '@/locales';

import { useAppStore } from '@/store/modules/app';

import { downloadFile } from '@/utils/z';

import { fetchAuthDmRecycleExport, fetchAuthDmRecycleResidual, fetchDeleteDmRecycleResidual, fetchGetDmRecycleResidualPage } from '@/service/api';

import RecycleResidualSearch from './models/recycle-residual-search.vue';

import RecycleResidualOperateModal from './models/recycle-residual-operate-modal.vue';
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'DmRecycleResidualPage'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const appStore = useAppStore();

const { hasAuth, currentOrgPosition } = useAuth();
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++
export type OperateType = NaiveUI.TableOperateType | 'view';

const operateType = ref<OperateType>('add');

const editingData: Ref<Api.Dimo.DmRecycleResidual | null> = ref(null);
// ---------- 业务模型 ----------

const orgType = ref<string>(currentOrgPosition()?.orgType || '');

const authRejectReason = ref<string>('');
// ---------- 业务方法 ----------
const renderButton = (row: Api.Dimo.DmRecycleResidual, status: boolean) => {
  return (
    <NButton type="primary" quaternary size="small" onClick={() => handleAuth(row.id, status ? '0' : '1')}>
      {status ? '回退' : '审核'}
    </NButton>
  );
};

const renderAuthButton = (row: Api.Dimo.DmRecycleResidual) => {
  console.log(row, orgType.value, 'renderAuthButton');
  if (orgType.value === 'County' && !row.cityAuthStatus && !row.provinceAuthStatus) {
    return renderButton(row, row.countyAuthStatus);
  } else if (orgType.value === 'City' && !row.provinceAuthStatus) {
    return renderButton(row, row.cityAuthStatus);
  } else if (orgType.value === 'Province') {
    return renderButton(row, row.provinceAuthStatus);
  }
  return null;
};

const { columns, columnChecks, data, loading, getData, getDataByPage, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetDmRecycleResidualPage,
  showTotal: true,
  apiParams: {
    page: 1,
    pageSize: 20,
    reportUnit: null,
    orgName: null,
    reportPerson: null,
    authStatus: null
  },
  columns: () => [
    {
      type: 'selection',
      width: 48,
      align: 'center'
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'surveyPointId',
      title: $t('page.dimo.recycle.surveyPointId'),
      align: 'left',
      minWidth: 100
    },
    {
      key: 'orgId',
      title: '市/县',
      align: 'left',
      minWidth: 100,
      render: (row) => <div>{row.provinceCityCountyInfo.cityName + row.provinceCityCountyInfo.countyName}</div>
    },
    {
      key: 'reportDate',
      title: $t('page.dimo.recycle.reportDate'),
      align: 'center',
      width: 110,
      render: (row) => dayjs(row.reportDate).format('YYYY-MM-DD')
    },
    {
      key: 'reportPerson',
      title: $t('page.dimo.recycle.reportPerson'),
      align: 'center',
      width: 110
    },
    {
      key: 'reportPersonContactInfo',
      title: '联系方式',
      align: 'center',
      width: 120
    },
    {
      key: 'countyAuthUserId',
      title: '审核（区/县）',
      align: 'center',
      children: [
        {
          key: 'countyAuthStatus',
          align: 'center',
          title: '状态',
          width: 70,
          render: (row) => {
            if (row.countyAuthStatus) {
              return (
                <n-tag type="success" size="small">
                  &nbsp;√&nbsp;
                </n-tag>
              );
            }
            return '';
          }
        },
        {
          key: 'countyAuthDate',
          align: 'center',
          title: '日期',
          width: 110,
          render: (row) => {
            if (row.countyAuthStatus && row.countyAuthDate) {
              return dayjs(row.countyAuthDate).format('YYYY-MM-DD');
            }
            return '';
          }
        }
      ]
    },
    {
      key: 'cityAuthUserId',
      align: 'center',
      title: '审核（市）',
      children: [
        {
          key: 'cityAuthStatus',
          align: 'center',
          title: '状态',
          width: 70,
          render: (row) => {
            if (row.cityAuthStatus) {
              return (
                <n-tag type="success" size="small">
                  &nbsp;√&nbsp;
                </n-tag>
              );
            }
            return '';
          }
        },
        {
          key: 'cityAuthDate',
          align: 'center',
          title: '日期',
          width: 110,
          render: (row) => {
            if (row.cityAuthStatus && row.cityAuthDate) {
              return dayjs(row.cityAuthDate).format('YYYY-MM-DD');
            }
            return '';
          }
        }
      ]
    },
    {
      key: 'provinceAuthUserId',
      align: 'center',
      title: '审核（省）',
      children: [
        {
          key: 'provinceAuthStatus',
          align: 'center',
          title: '状态',
          width: 70,
          render: (row) => {
            if (row.provinceAuthStatus) {
              return (
                <n-tag type="success" size="small">
                  &nbsp;√&nbsp;
                </n-tag>
              );
            }
            return '';
          }
        },
        {
          key: 'provinceAuthDate',
          align: 'center',
          title: '日期',
          width: 110,
          render: (row) => {
            if (row.provinceAuthStatus && row.provinceAuthDate) {
              return dayjs(row.provinceAuthDate).format('YYYY-MM-DD');
            }
            return '';
          }
        }
      ]
    },
    {
      key: 'comment',
      title: $t('page.dimo.recycle.comment'),
      align: 'left',
      width: 110
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 180,
      minWidth: 180,
      render: (row) => (
        <div class="flex-center gap-8px">
          <NButton type="primary" quaternary size="small" onClick={() => view(row)}>
            详情
          </NButton>
          {hasAuth('dm:residual:auth') && renderAuthButton(row)}
          {hasAuth('dm:residual:update') && !row.countyAuthStatus && !row.cityAuthStatus && !row.provinceAuthStatus && (
            <NButton type="primary" quaternary size="small" onClick={() => edit(row)}>
              {$t('common.edit')}
            </NButton>
          )}
          {hasAuth('dm:residual:delete') && (
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" quaternary size="small">
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          )}
        </div>
      )
    }
  ]
});
const { drawerVisible, openDrawer, checkedRowKeys, onDeleted, onBatchDeleted } = useTableOperate(data, getData);

function view(item: Api.Dimo.DmRecycleResidual) {
  operateType.value = 'view';
  console.log(item, 'item');
  editingData.value = { ...item };
  openDrawer();
}

async function handleAuth(id: string, status: string) {
  window.$dialog?.info({
    title: $t('common.tip'),
    content: () => {
      if (status === '0') {
        return (
          <div>
            <n-input
              v-model={authRejectReason.value}
              type="textarea"
              maxlength="200"
              show-count={true}
              placeholder="请输入审核意见"
              onUpdateValue={(val: string) => (authRejectReason.value = val)}
            />
          </div>
        );
        // eslint-disable-next-line no-else-return
      } else {
        return `是否确定进行审核操作?`;
      }
    },
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const parama = {
        id,
        status,
        authRejectReason: authRejectReason.value
      };
      const { error, data: result } = await fetchAuthDmRecycleResidual(parama);
      if (!error && result) {
        getData();
        window.$message?.success('操作成功!');
      }
    },
    onNegativeClick: async () => {}
  });
}

/**
 * 处理添加操作
 *
 * 将操作类型设置为'add'，并调用 openDrawer 函数打开抽屉组件
 */
function handleAdd() {
  operateType.value = 'add';
  openDrawer();
}
function edit(item: Api.Dimo.DmRecycleResidual) {
  operateType.value = 'edit';
  editingData.value = { ...item };
  openDrawer();
}

async function handleDelete(id: string) {
  // request
  const { error, data: result } = await fetchDeleteDmRecycleResidual(transDeleteParams([id]));
  if (!error && result) {
    await onDeleted();
  }
}
// 删除操作
async function handleBatchDelete() {
  // request
  const { error, data: result } = await fetchDeleteDmRecycleResidual(transDeleteParams(checkedRowKeys.value));
  if (!error && result) {
    await onBatchDeleted();
  }
}

const checkedRowKeysRef = ref<DataTableRowKey[]>([]);
// 批量
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeysRef.value = rowKeys;
};

/** 导出 */
// eslint-disable-next-line consistent-return
const downloadTemplate = async (ids: any) => {
  // eslint-disable-next-line eqeqeq
  const info = await fetchAuthDmRecycleExport({ ids });
  const { data: result } = info;
  const blob = result;

  // // 检查响应头判断是否Excel文件
  if (info.response.headers['content-type'].includes('spreadsheetml.sheet')) {
    downloadFile('使用回收情况入户抽样调查.xlsx', blob);
  } else {
    // 尝试解析为JSON
    const text = await new Response(info.response?.data as any).text();
    window.$message?.error(JSON.parse(text).message);
  }
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-8px overflow-hidden lt-sm:overflow-auto">
    <RecycleResidualSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard :bordered="false" class="sm:flex-1-hidden card-wrapper" content-class="flex-col">
      <TableHeaderOperation
        v-model:columns="columnChecks"
        :checked-row-keys="checkedRowKeys"
        :loading="loading"
        add-auth="dm:residual:add"
        delete-auth="dm:residual:delete"
        export-auth="dm:residual:exportData"
        @add="handleAdd"
        @delete="handleBatchDelete"
        @export-excel="downloadTemplate(checkedRowKeys)"
      />
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        remote
        striped
        size="small"
        class="sm:h-full"
        :data="data"
        :scroll-x="962"
        :columns="columns"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        :single-line="false"
        :row-key="(row) => row.id"
        :pagination="mobilePagination"
        @update:checked-row-keys="handleCheck"
      />
      <RecycleResidualOperateModal v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData" @submitted="getDataByPage" />
    </NCard>
  </div>
</template>
